package lib

import (
	"crypto/tls"
	"fmt"
	"github.com/beevik/etree"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

func AccountDiscover(url, fqdn ,emailAddr string) (legaDN, serverDN string) {
	data := `<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/2006"><Request><EMailAddress>`+emailAddr+`</EMailAddress> <AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/responseschema/2006a</AcceptableResponseSchema></Request></Autodiscover>`
	cli := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}, Timeout: time.Second * 5}
	request, err := http.NewRequest(http.MethodPost, url, strings.NewReader(data))
	if err != nil {
		panic(err)
	}
	request.Header.Add("Cookie", "X-BEResource="+fqdn+"/autodiscover/autodiscover.xml?a=~1942062522;")
	request.Header.Add("Content-Type", "text/xml")
	request.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:86.0) Gecko/20100101 Firefox/86.0")
	request.Header.Add("Accept", "*/*")
	request.Header.Add("Connection", "keep-alive")
	request.Header.Add("Content-Length", strconv.Itoa(len(data)))
	do, err := cli.Do(request)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = do.Body.Close()
	}()
	if do.StatusCode != http.StatusOK {
		fmt.Println("[x] Response Status Code Is Bad")
		os.Exit(0)
	}
	all, err := ioutil.ReadAll(do.Body)
	if err != nil {
		panic(err)
	}
	doc := etree.NewDocument()
	err = doc.ReadFromString(string(all))
	if err != nil {
		panic(err)
	}
	legacyDNtext := doc.FindElement("Autodiscover/Response/User/LegacyDN").Text()
	serverDNtext := doc.FindElement("Autodiscover/Response/Account/Protocol/ServerDN").Text()
	replace := strings.Split(serverDNtext, "/cn=Servers/cn=")
	split := strings.Split(replace[1], "@")
	return legacyDNtext, split[0]

}
